package br.com.winesys.geta.persistence.jdbc;

import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Date;
import org.apache.commons.beanutils.MethodUtils;
import org.apache.commons.beanutils.PropertyUtils;

public final class JDBCObjectFiller {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static void fillObject(Object object, ResultSet resultSet) {
		try {
			ResultSetMetaData metadata = resultSet.getMetaData();
			for (int i = 1; i <= metadata.getColumnCount(); i++) {
				String columnName = metadata.getColumnName(i);

				Class propertyType = PropertyUtils.getPropertyType(object, columnName);
				if (propertyType.equals(String.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getString(columnName));
				} else if (propertyType.equals(Character.class)) {
					PropertyUtils.setProperty(object, columnName, Character.valueOf(resultSet.getString(columnName).charAt(0)));
				} else if (propertyType.equals(Date.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getDate(columnName));
				} else if (propertyType.equals(Boolean.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getBoolean(columnName));
				} else if (propertyType.equals(Byte.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getByte(columnName));
				} else if (propertyType.equals(Integer.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getInt(columnName));
				} else if (propertyType.equals(Long.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getLong(columnName));
				} else if (propertyType.equals(Float.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getFloat(columnName));
				} else if (propertyType.equals(Double.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getDouble(columnName));
				} else if (propertyType.equals(BigDecimal.class)) {
					PropertyUtils.setProperty(object, columnName, resultSet.getBigDecimal(columnName));
				} else if (propertyType.isEnum()) {
					Object value;
					String queryResult = resultSet.getString(columnName);
					if (queryResult != null) {
						try {
							value = MethodUtils.invokeStaticMethod(propertyType, "parse", queryResult);
						} catch (Exception ex) {
							value = Enum.valueOf(propertyType, queryResult);
						}
						PropertyUtils.setProperty(object, columnName, value);
					}
				}

			}
		} catch (Exception ex) {
			throw new RuntimeException("Não foi possível recuperar os dados da consulta.", ex);
		}
	}
}
